package config

import (
	"encoding/json"
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"github.com/spf13/viper"
)

type ApiConfig struct {
	Mysql  Mysql  `mapstructrue:"mysql" json:"mysql"`
	Redis  Redis  `mapstructrue:"redis" json:"redis"`
	Consul Consul `mapstructrue:"consul" json:"consul"`
}
type Nacos struct {
	IpAddr      string `mapstructrue:"ipAddr" json:"ipAddr"`
	Port        uint64 `mapstructrue:"port" json:"port"`
	DataId      string `mapstructrue:"dataId" json:"dataId"`
	NameSpaceId string `mapstructrue:"nameSpaceId" json:"nameSpaceId"`
	Group       string `mapstructrue:"group" json:"group"`
}
type Mysql struct {
	User     string `mapstructrue:"user" json:"user"`
	Password string `mapstructrue:"password" json:"password"`
	Host     string `mapstructrue:"host" json:"host"`
	Port     int    `mapstructrue:"port" json:"port"`
	Database string `mapstructrue:"database" json:"database"`
}
type Redis struct {
	Addr     string `mapstructrue:"addr" json:"addr"`
	Password string `mapstructrue:"password" json:"password"`
	DB       int    `mapstructrue:"DB" json:"DB"`
}
type Consul struct {
	Host string `mapstructrue:"host" json:"host"`
	Port int    `mapstructrue:"port" json:"port"`
}

var (
	GlobalConfig ApiConfig
	NacosConfig  Nacos
)

func ConfigInit(nameSpaceId string, ipAddr string, port uint64, dataId string, group string) (Nacos, ApiConfig) {
	v := viper.New()
	v.SetConfigFile("E:\\gowork\\src\\GolandProjects\\like-shop-common-package\\shop.yaml")
	err := v.ReadInConfig()
	if err != nil {
		panic(err)
	}
	nacosconfig := Nacos{}
	v.Unmarshal(&nacosconfig)
	NacosConfig = nacosconfig
	clientConfig := constant.ClientConfig{
		NamespaceId:         nameSpaceId, //we can create multiple clients with different namespaceId to support multiple namespace.When namespace is public, fill in the blank string here.
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
		LogLevel:            "debug",
	}
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      ipAddr,
			ContextPath: "/nacos",
			Port:        port,
			Scheme:      "http",
		},
	}
	client, _ := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})
	content, err := client.GetConfig(vo.ConfigParam{
		DataId: dataId,
		Group:  group})
	globalconfig := ApiConfig{}
	json.Unmarshal([]byte(content), &globalconfig)
	GlobalConfig = globalconfig
	return NacosConfig, GlobalConfig
}
